package com.sunday.aomicaichang.ui;

import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.ui.widgets.PopBuyMallWindow;
import com.sunday.aomicaichang.widgets.ShareWindow;
import com.sunday.member.constv.ConstValue;
import com.sunday.member.entity.product.ProductDetail;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.math.RoundingMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/6/5.
 */

public class MallFoodDetailActivity extends BaseActivity {

    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_integral)
    TextView tvIntegral;
    @Bind(R.id.tv_price)
    TextView tvPrice;
    @Bind(R.id.tv_send_price)
    TextView tvSendPrice;
    @Bind(R.id.nested_scroll_webview1)
    WebView webView;
    @Bind(R.id.btn_next)
    TextView btnNext;
    @Bind(R.id.img)
    ImageView img;
    @Bind(R.id.view)
    View view;
    @Bind(R.id.integral)
    TextView integral;
    @Bind(R.id.tv1)
    TextView tv1;
    @Bind(R.id.ly)
    RelativeLayout ly;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.right_menu)
    ImageView rightMenu;
    @Bind(R.id.title_bar)
    RelativeLayout titleBar;
    private long productId;
    private ProductDetail productDetail;
    private int villageId;
    private PopBuyMallWindow popBuyWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity_detail);
        ButterKnife.bind(this);
        villageId = SharePerferenceUtils.getIns(mContext).getInt(com.sunday.aomicaichang.constValues.ConstValue.AREA, 0);
        productId = getIntent().getLongExtra("productId", 0);
        getData();
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popBuyWindow == null) {
                    popBuyWindow = new PopBuyMallWindow(mContext, ConstValue.TYPE_BUY_NOW, productDetail.getImage(), productDetail.getId(), String.format("%s", productDetail.getPrice().setScale(2, RoundingMode.HALF_UP)),
                            productDetail.getSaleNumber(),productDetail.getMarketPrice());
                } else {
                    popBuyWindow.setBuyType(ConstValue.TYPE_BUY_NOW);
                }
                popBuyWindow.showPopupWindow(btnNext);
            }
        });
        rightMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(productDetail.getShareUrl()==null||productDetail.getShareTitle()==null){
                    ToastUtils.showToast(mContext,"数据不完整");
                    return;
                }
                ShareWindow shareWindow=new ShareWindow(mContext,productDetail.getShareUrl(),productDetail.getName(),productDetail.getImage(),productDetail.getShareDesc());
                shareWindow.showPopupWindow(rightMenu);
            }
        });
    }

    private void getData() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"productId", "villageId", "nonce"};
        String[] str2 = new String[]{String.valueOf(productId), String.valueOf(villageId), nonce};
        showLoadingDialog(0);
        Call<ResultDO<ProductDetail>> call = MemberClient.getApiAdapter().getProductDetail(productId, villageId, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<ProductDetail>>() {
            @Override
            public void onResponse(Call<ResultDO<ProductDetail>> call, Response<ResultDO<ProductDetail>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    productDetail = response.body().getResult();
                    updateView();

                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<ProductDetail>> call, Throwable t) {
                dissMissDialog();
            }
        });
    }

    private void updateView() {
        if (productDetail == null) {
            return;
        }

        tvName.setText(productDetail.getName());
        tvIntegral.setText(productDetail.getPrice() + "");
        if (productDetail.getMarketPrice() == null) {
            tvPrice.setText("");
        } else {
            tvPrice.setText(String.format("￥%s",productDetail.getMarketPrice().setScale(2,RoundingMode.HALF_UP)));
            tvPrice.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG|Paint.STRIKE_THRU_TEXT_FLAG);
        }
        if (productDetail.getImage() != null)
            Picasso.with(mContext)
                    .load(productDetail.getImage())
                    .error(R.mipmap.ic_product)
                    .into(img);

        //启用支持javascript
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setBuiltInZoomControls(false);
        settings.setSupportZoom(false);
        settings.setDomStorageEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!TextUtils.isEmpty(url)) {
                    view.loadUrl(url);
                } else {
                    dissMissDialog();
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dissMissDialog();
            }
        });
        webView.loadUrl(MemberClient.PRODUCT_DETAIL_URL + String.valueOf(productId));

    }
}
